import {Component} from 'react';
import React from 'react';
import {connect} from 'umi';
import HighPerformTable from '@/components/HighPerformTableSpecially';
import APIS from '@/apis';
import SearchAbleSelect from '@/components/SearchAbleSelect';
import {Button, Divider, Input, message, Select, Upload} from 'antd';
import CustomCascader from '@/components/CustomCascader/CustomCascader';
import {DownloadOutlined, PlusOutlined, UploadOutlined} from '@ant-design/icons';
import Modal from 'antd/lib/modal/Modal';
import Form from 'antd/lib/form/Form';
import FormItem from 'antd/lib/form/FormItem';
import {FormInstance} from 'antd/es/form';
import * as PP from 'papaparse'

const prefix = ""

class StudentManagerPage extends Component<any, any> {
  actionRef: any;
  createRef: FormInstance;
  importRef: FormInstance;
  classId = -1;

  constructor(props: any) {
    super(props);
  }

  state = {
    createVisible: false,
    importVisible: false,
    schoolId: 0,
    collageId: 0,
    majorId: 0,
    classId: 0,
    filterSchoolId: 0,
    filterCollageId: 0,
    filterMajorId: 0,
    filterClassId: 0,
  }

  requestGetData(
    params: {
      pageSize?: number;
      current?: number;
    },
    sorter: {
      [key: string]: 'ascend' | 'descend';
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) {
    const {filterSchoolId, filterClassId, filterCollageId, filterMajorId} = this.state;
    return APIS.OrgsAPI.GetStudentList({
      ...params,
      sorter,
      filter,
      id: filterClassId || -1,
      school: filterSchoolId,
      college: filterCollageId,
      major: filterMajorId,
    });
  }

  handleDelete(data: any) {
    return APIS.OrgsAPI.DeleteStudent({id: data.id})
      .then(res => this.actionRef.reload())
      .catch(() => {
        return Promise.resolve(false);
      });
  }


  componentDidMount() {
  }

  clomns: any = [
    {
      title: '姓名',
      dataIndex: 'trueName',
      rules: [
        {
          required: true,
          message: '规则名称为必填项',
        },
      ],
    },
    {
      title: '学号',
      dataIndex: 'studentId',
    },
    {
      title: '班级',
      dataIndex: 'class',
      render: (item: any) => {
        return <span>{item.classIndex}</span>;
      },
      renderFormItem: (item: any, config: any, form: any) => (
        <div style={{display: 'flex', flexDirection: 'row'}}>
          <SearchAbleSelect
            searchData={async (key) => {
              var datas: Array<any> = await APIS.OrgsAPI.SearchTeacher(key);
              return Promise.resolve(
                datas.map((item) => {
                  return {value: item.id, key: item.name};
                }),
              );
            }}
            form={form}
            name="teacher"
          ></SearchAbleSelect>
          <SearchAbleSelect
            searchData={async (key) => {
              var datas: Array<any> = await APIS.OrgsAPI.SearchTeacher(key);
              return Promise.resolve(
                datas.map((item) => {
                  return {value: item.id, key: item.name};
                }),
              );
            }}
            form={form}
            name="teacher"
          ></SearchAbleSelect>
          <SearchAbleSelect
            searchData={async (key) => {
              var datas: Array<any> = await APIS.OrgsAPI.SearchTeacher(key);
              return Promise.resolve(
                datas.map((item) => {
                  return {value: item.id, key: item.name};
                }),
              );
            }}
            form={form}
            name="teacher"
          ></SearchAbleSelect>
        </div>
      ),
    },
    {
      title: '年级',
      dataIndex: 'class',
      render: (item: any) => {
        return <span>{item.grade}</span>;
      },
      hideInForm: true,
    },
    {
      title: '专业',
      dataIndex: 'class',
      hideInForm: true,
      render: (item: any) => {
        return item.majorInfo?.majorName;
      },
    },
    {
      title: '学院',
      dataIndex: 'collage',
      hideInForm: true,
      hideColumn: true,
      render: (item: any) => {
        return item.majorInfo?.collegeData?.name;
      },
    },
    {
      title: '更新时间',
      hideInForm: true,
      dataIndex: 'updatedTime',
      valueType: 'datetime',
    },
    {
      title: '审核',
      hideInForm: true,
      dataIndex: 'class',
      valueType: 'datetime',
      render: (item: any, data: any) => {
        return <div>
          {
            data.state === 1 ? "已启用" :
              <div><Button type="primary"
                           onClick={() => APIS.OrgsAPI.AcceptStudentInfo(data).then(() => this.actionRef.reload())}>同意</Button>
                <Divider type="vertical"></Divider>
                <Button type="ghost"
                        onClick={() => APIS.OrgsAPI.RefuseStudentInfo(data).then(() => this.actionRef.reload())}>拒绝</Button>
              </div>
          }
        </div>
      },
    }
  ];

  handleChangeFilter(data: any) {


    this.setState({
      filterSchoolId: data[0] ? data[0] : 0,
      filterCollageId: data[1] ? data[1] : 0,
      filterMajorId: data[2] ? data[2] : 0,
      filterClassId: data[3] ? data[3] : 0,
    })


    // this.createRef.
  }

  handleDataImport() {
  }

  handleDataExport() {
  }

  render() {
    const {filterClassId, filterCollageId, filterMajorId, filterSchoolId} = this.state;
    return (
      <div>
        <CustomCascader
          datasource={[{
            placeholder: "请选择学校",

            dataGet: (values) => APIS.OrgsAPI.SearchGetSchoolList({current: 1, pageSize: 100}),
            renderOption: (data) => {
              return <Select.Option key={data.id} value={data.id}>{data.name}</Select.Option>
            }
          }, {
            placeholder: "请选择院系",
            dataGet: (values) => APIS.OrgsAPI.GetCollegeListBySchool({
              current: 1,
              pageSize: 100,
              id: values[0]
            }).then((res) => res.data), renderOption: (data) => {
              return <Select.Option key={data.id} value={data.id}>{data.collegeName}</Select.Option>
            }
          }, {
            placeholder: "请选择专业",
            dataGet: (values) => APIS.OrgsAPI.GetCollegeMajorList({id: values[1]}), renderOption: (data) => {
              return <Select.Option key={data.id} value={data.id}>{data.majorName}</Select.Option>
            }
          }, {
            placeholder: "请选择班级",
            dataGet: (values) => APIS.OrgsAPI.GetMajorClassList({id: values[2]}), renderOption: (data) => {
              return <Select.Option key={data.id} value={data.id}>{`${data.grade}级${data.classIndex}班`}</Select.Option>
            }
          }]}
          onChange={data => {
            this.classId = data[3];
            this.actionRef.reload()
            this.handleChangeFilter(data);
          }}></CustomCascader>
        <HighPerformTable<any>
          ref={(ref) => (this.actionRef = ref)}
          columns={this.clomns}

          toolBarRender={() => [
            <Button type="primary" onClick={() => this.setState({createVisible: true})}>
              <PlusOutlined/> 新增学生
            </Button>,
            <Button type="primary" onClick={() => this.setState({importVisible: true})}>
              <DownloadOutlined/> 批量导入
            </Button>,
          ]}
          //action
          // additionOptions={[{
          //   title: "删除", onClick: (data) => {
          //      APIS.OrgsAPI.DeleteStudent({ id: data.id }).then(res=>this.actionRef.reload())
          //     // console.log(data);

          //   }
          // }]}
          requestGetData={this.requestGetData.bind(this)}
          handleDelete={this.handleDelete.bind(this)}
        />
        <Modal okText="确定" destroyOnClose={true} onOk={() => {
          this.createRef.submit();
        }} cancelText="取消" visible={this.state.createVisible} onCancel={() => {
          this.setState({createVisible: false});
          this.createRef.resetFields();
        }} closable={false}>
          <Form ref={(ref) => this.createRef = ref} onFinish={(values) => {
            this.createRef.validateFields().then(() => {
              APIS.OrgsAPI.CreateNewStudent(values).then(() => {
                this.actionRef.reload();
                this.createRef.resetFields()
                this.setState({createVisible: false})
              })
            })
          }}>
            <FormItem name="studentName" required rules={[{required: true, message: "请输入姓名"}]} label="姓名">
              <Input></Input>
            </FormItem>
            <FormItem name="studentId" rules={[{required: true, message: "请输入学号"}]} required label="学号">
              <Input></Input>
            </FormItem>
            <FormItem name="classId" required rules={[{required: true, message: "请选择班级"}]} label="班级">
              <CustomCascader
                initValues={[filterSchoolId, filterCollageId, filterMajorId, filterClassId]}
                datasource={[{
                  placeholder: "请选择学校",
                  defaultValue: this.state.filterSchoolId === 0 ? undefined : this.state.filterSchoolId,
                  dataGet: (values) => APIS.OrgsAPI.SearchGetSchoolList({current: 1, pageSize: 100}),
                  renderOption: (data) => {
                    return <Select.Option key={data.id} value={data.id}>{data.name}</Select.Option>
                  }
                }, {
                  placeholder: "请选择院系",
                  defaultValue: this.state.filterCollageId === 0 ? undefined : this.state.filterCollageId,
                  dataGet: (values) => APIS.OrgsAPI.GetCollegeListBySchool({
                    current: 1,
                    pageSize: 100,
                    id: values[0]
                  }).then((res) => res.data), renderOption: (data) => {

                    return <Select.Option key={data.id} value={data.id}>{data.collegeName}</Select.Option>
                  }
                }, {
                  placeholder: "请选择专业",
                  defaultValue: this.state.filterMajorId === 0 ? undefined : this.state.filterMajorId,
                  dataGet: (values) => APIS.OrgsAPI.GetCollegeMajorList({id: values[1]}), renderOption: (data) => {
                    return <Select.Option key={data.id} value={data.id}>{data.majorName}</Select.Option>
                  }
                }, {
                  placeholder: "请选择班级",
                  defaultValue: this.state.filterClassId === 0 ? undefined : this.state.filterClassId,
                  dataGet: (values) => APIS.OrgsAPI.GetMajorClassList({id: values[2]}), renderOption: (data) => {
                    return <Select.Option key={data.id}
                                          value={data.id}>{`${data.grade}级${data.classIndex}班`}</Select.Option>
                  }
                }]}
                onChange={(data) => {
                  this.createRef.setFieldsValue({classId: data[3]})
                  //  this.handleChangeFilter(data);
                  //  console.log(data);
                }
                }></CustomCascader>
            </FormItem>
          </Form>
        </Modal>
        <Modal okText="确定" cancelText="取消" visible={this.state.importVisible} onCancel={() => {
          this.setState({importVisible: false});
          this.importRef.resetFields();
        }} closable={false} onOk={() => {
          this.importRef.submit();
        }}>
          <Form ref={ref => this.importRef = ref} onFinish={(values) => {
            this.importRef.validateFields().then(() => {
              const hide = message.loading('正在导入', 1000);
              APIS.OrgsAPI.ImportStudents(values).then(() => {
                this.actionRef.reload();
                this.importRef.resetFields();
                this.setState({importVisible: false})
              }).then(() => {
                hide();
                message.success('导入成功');
              }).catch(() => {
                hide();
                message.success('导入成功');
              })
            })
          }}>
            <FormItem name="datas" label="文件" required rules={[{required: true, message: "请选择文件"}]}>
              <Upload accept={".csv"} onChange={(ev) => {
                var datas = []
                var that = this;
                PP.parse(ev.file.originFileObj, {
                  complete: function (results) {
                    //studentId,trueName
                    // console.log()
                    // console.log(results)
                    let isGrammarCSV = results.data[0][0] === "studentId"
                    if (results.data[0][0] === "学号") {
                      isGrammarCSV = true;
                    }

                    for (let index = 1; index < results.data.length; index++) {
                      const item = results.data[index];
                      var p: any = {}
                      if (isGrammarCSV) {
                        p.studentId = prefix + item[0];
                        p.studentName = item[1];
                      } else {
                        p.studentId = prefix + item[1];
                        p.studentName = item[0];
                      }
                      datas.push(p);
                    }
                    that.importRef.setFieldsValue({datas: datas})
                  }
                });
              }}>
                <Button icon={<UploadOutlined/>}>点击上传</Button>
              </Upload>
            </FormItem>
            <FormItem name="classId" label="班级" required rules={[{required: true, message: "请选择班级"}]}>
              <CustomCascader datasource={[{
                placeholder: "请选择学校",
                dataGet: (values) => APIS.OrgsAPI.SearchGetSchoolList({current: 1, pageSize: 100}),
                renderOption: (data) => {
                  return <Select.Option key={data.id} value={data.id}>{data.name}</Select.Option>
                }
              }, {
                placeholder: "请选择院系",
                dataGet: (values) => APIS.OrgsAPI.GetCollegeListBySchool({
                  current: 1,
                  pageSize: 100,
                  id: values[0]
                }).then((res) => res.data), renderOption: (data) => {
                  return <Select.Option key={data.id} value={data.id}>{data.collegeName}</Select.Option>
                }
              }, {
                placeholder: "请选择专业",
                dataGet: (values) => APIS.OrgsAPI.GetCollegeMajorList({id: values[1]}), renderOption: (data) => {
                  return <Select.Option key={data.id} value={data.id}>{data.majorName}</Select.Option>
                }
              }, {
                placeholder: "请选择班级",
                dataGet: (values) => APIS.OrgsAPI.GetMajorClassList({id: values[2]}), renderOption: (data) => {
                  return <Select.Option key={data.id}
                                        value={data.id}>{`${data.grade}级${data.classIndex}班`}</Select.Option>
                }
              }]}
                              onChange={(data) => {

                                this.importRef.setFieldsValue({classId: data[3]})
                                // console.log(data);

                              }}></CustomCascader>
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default connect()(StudentManagerPage);
